import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, DatePicker, Divider, Form, Modal, Space, Upload, UploadFile } from 'antd';
import dayjs from 'dayjs';
import Saver from 'file-saver';

import { store } from '@/store';

import { NumBool } from '@/enum';
import {
  proDataRevenueYearDownloadTemplate,
  proDataRevenueYearImport
} from '@/services/bizApi/nianyingshouqingkuangjiekou';
import { Icon } from '@iconify/react/dist/iconify.js';

import { BizObamountct } from '.';

export type ImportRef = {
  open: (arg: { rowData?: BizObamountct; onSuccess: () => void }) => void;
};

export type ImportProps = {};

const Import: React.ForwardRefRenderFunction<ImportRef, ImportProps> = (props, ref) => {
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<ImportRef['open']>[0]>();
  // 下载导入模板
  const downloadTemplate = useRequest(
    async () => {
      const res = await proDataRevenueYearDownloadTemplate({
        method: 'POST',
        responseType: 'blob'
      });

      // 获取文件名
      const contentDisposition = res.headers['content-disposition'];
      let filename = '';

      if (contentDisposition && contentDisposition.indexOf('attachment') !== -1) {
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        const matches = filenameRegex.exec(contentDisposition);
        if (matches !== null && matches[1]) {
          filename = decodeURIComponent(matches[1].replace(/['"]/g, ''));
        }
      }

      Saver.saveAs(res.data, filename);
    },
    {
      manual: true
    }
  );
  // 提交表单
  const submit = useRequest(
    async (values) => {
      console.log(values);
      const formData = new FormData();
      formData.append('file', fileList[0].originFileObj!);

      await proDataRevenueYearImport(
        { year: dayjs(values.year).format('YYYY') as unknown as number } as ArgumentsType<
          typeof proDataRevenueYearImport
        >[0],
        {},
        {
          method: 'POST',
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          data: formData,
          timeout: 60000
        }
      );

      store.app?.message.success('导入成功');
      setOpen(false);
      args?.onSuccess();
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 清空表单
          form.resetFields();
          form.setFieldsValue({
            cover: NumBool.是
          });
        });
      }
    };
  });

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在导入，请稍后再试');

      return;
    }

    setOpen(false);
  };

  return (
    <Modal
      title="导入年营收目标"
      open={open}
      onCancel={onCancel}
      onOk={form.submit}
      okButtonProps={{
        loading: submit.loading,
        disabled: submit.loading
      }}
      cancelButtonProps={{
        disabled: submit.loading
      }}
      footer={(originNode) => {
        return (
          <Space>
            <Button
              type="primary"
              onClick={downloadTemplate.run}
              disabled={downloadTemplate.loading}
              loading={downloadTemplate.loading}
              icon={<Icon icon="ri:download-2-fill" />}
            >
              下载导入模板
            </Button>

            <Divider type="vertical" />

            {originNode}
          </Space>
        );
      }}
    >
      <Form style={{ marginTop: 20 }} onFinish={submit.run} form={form}>
        <Form.Item label="年份" rules={[{ required: true, message: '请选择导入年份' }]} name="year">
          <DatePicker picker="year" placeholder={'请选择导入年份'} format="YYYY" />
        </Form.Item>
        <Form.Item
          label="文件"
          name="file"
          rules={[{ required: true, message: '请选择文件' }]}
          valuePropName="fileList"
          getValueFromEvent={(e) => e.fileList}
        >
          <Upload.Dragger
            maxCount={1}
            accept=".xls,.xlsx"
            beforeUpload={() => false}
            fileList={fileList}
            onChange={(info) => {
              setFileList(info.fileList);
            }}
          >
            <div>点击上传</div>
          </Upload.Dragger>
        </Form.Item>
        {/* <Form.Item label="字典值存在时是否覆盖" name="cover">
          <Radio.Group>
            {Array.from(NumBoolObj).map(([value, label]) => (
              <Radio value={value} key={value}>
                {label.text}
              </Radio>
            ))}
          </Radio.Group>
        </Form.Item> */}
      </Form>
      <div style={{ color: 'red', textAlign: 'center' }}>
        注意：导入后数据将覆盖原有数据，请谨慎操作。
      </div>
    </Modal>
  );
};

export default forwardRef(Import);
